package com.imooc.authorization.controller;

import com.imooc.authorization.common.Whether;
import com.imooc.authorization.context.LoginUserCache;
import com.imooc.authorization.context.NativeCache;
import com.imooc.authorization.context.UserContext;
import com.imooc.authorization.dto.Accordion;
import com.imooc.authorization.entity.*;
import com.imooc.authorization.service.RoleService;
import com.imooc.authorization.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.*;

/**
 * Created by Administrator on 2016/8/26.
 */
@Controller
public class LoginController {

    @Autowired private UserService userService;
    @Autowired private NativeCache nativeCache;
    @Autowired private RoleService roleService;

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String index(){

        return "security/login";
    }
    //TODO 待修改
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(Model model, String name, String pwd){
        User user = userService.getUser(name,pwd);

        if(null==user){

            return "security/login";
        }

        try {
            LoginUserCache.put(user,30*60);

            if(Objects.equals("admin",user.getName())){

                model.addAttribute("accordions",getAccordions(true,null));
            }else{
                List<UserRole> userRoles=userService.getUserRolesByUserId(user.getId());
                if(null==userRoles||0==userRoles.size()){
                    model.addAttribute("msg","用户没有授权");
                    return "securiy/login";
                }
                List<Long> roleIds=new ArrayList<>();
                for(UserRole ur:userRoles){
                    roleIds.add(ur.getRoleId());
                }
               List<Role> roles= roleService.getRoles(roleIds);
                //登陆成功，将角色信息放入缓冲
                nativeCache.setRoles(user.getId(),roles);

                model.addAttribute("accordions",getAccordions(false,user.getId()));


            }

            return "layout/main";
        } catch (Exception e) {
            LoginUserCache.remove(user);
            return "security/login";
        }
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String logout(Model model,User user){

        LoginUserCache.remove(user);
        return "security/login";

    }


    private List<Accordion> getAccordions(boolean isAdmin,Long userId){
        Set<String> permissionUrls=new HashSet<>();
        Set<Long> rootFunctionIdSet=new HashSet<>();
        if(!isAdmin){
            for (Role role:nativeCache.getRoles(userId)){
                List<RoleFunction> roleFunctions=roleService.getRoleFunctions(role.getId());
                for (RoleFunction rf:roleFunctions){
                    Function func=nativeCache.getFunction(rf.getFunctionId());
                    if(Objects.equals(func.getAccordion(), Whether.YES.getValue())){
                        rootFunctionIdSet.add(func.getId());
                    }else {
                        permissionUrls.add(func.getUrl());
                    }
                }
            }
        }

        Map<Long,Accordion> accordionMap=new HashMap<>();
        List<Accordion> permissionAccordionSet = new LinkedList<>();

        List<Function> functions=nativeCache.getFunctions();

        List<Accordion> rootAccordionSet = new LinkedList<>();
        for (Function function:functions){
            Accordion accordion=new Accordion(function.getId(),function.getParentId(),function.getName(),function.getUrl(),function.getSerialNum());
            accordionMap.put(function.getId(),accordion);
            if (!isAdmin){
                if(permissionUrls.contains(function.getUrl())){

                    permissionAccordionSet.add(accordion);
                }
                if(rootFunctionIdSet.contains(function.getId())){

                    rootAccordionSet.add(accordion);
                }
            }else{
                permissionAccordionSet.add(accordion);
                if(Whether.YES.getValue()==function.getAccordion()){

                    rootAccordionSet.add(accordion);
                }
            }
        }
       Collections.sort(rootAccordionSet);
        Collections.sort(permissionAccordionSet);
        for(Accordion accordion:rootAccordionSet){

            completeAccordion(permissionAccordionSet,accordion);
        }


        return rootAccordionSet;
    }
    private void completeAccordion(List<Accordion> permissionAccordionSet,Accordion rootAccordion){
        for (Accordion accordion:permissionAccordionSet){
            if(Objects.equals(accordion.getParentId(),rootAccordion.getId())){

                rootAccordion.getChildren().add(accordion);
            }
        }

    }

}
